from rest_framework import serializers
from rest_framework.exceptions import ValidationError

from goods import models


class GoodsSer(serializers.ModelSerializer):
    brands = serializers.SerializerMethodField(read_only=True)
    def get_brands(self, obj):
        return obj.brand.name
    class Meta:
        model = models.Goods
        fields = '__all__'

    def validate_goodname(self, obj):
        a = models.Goods.objects.filter(goodname=obj).first()
        if a:
            raise ValidationError('商品名称已存在')
        if len(obj) < 4 or len(obj) > 15:
            raise ValidationError('商品名称长度不合法')
        return obj


class BrandSer(serializers.ModelSerializer):
    goods_set = GoodsSer(many=True)
    class Meta:
        model = models.Brand
        fields = '__all__'



    def validate_name(self, obj):
        a = models.Goods.objects.filter(name=obj).first()
        if a:
            raise serializers.ValidationError('商品名称已存在')
        if len(obj) < 2 or len(obj) > 10:
            raise serializers.ValidationError('商品名称长度不合法')
        return obj

